'use strict';

import {wsRest} from './ws_hfc.js';	
import {mycbops} from '../../imports/api/blocksmgr/chainblocks4mongo.js';
var path = require('path');
var fs = require('fs');
//var ws4rest = require('./ws_hfc.js');
													
var Ibc1 = require('ibm-blockchain-js');														//rest based SDK for ibm blockchain
var ibc = new Ibc1();
var chaincode = null;


class Hfc4Rest{
}

export const HfcRest = new Hfc4Rest();



HfcRest.prefer_type1_users=function(users,user_array){
        var ret = [];
        for(var i in users){
            if(users[i].enrollId.indexOf('type1') >= 0) {	//gather the type1 users
                ret.push(users[i]);
            }
        }

        if(ret.length === 0) ret = user_array;				//if no users found, just use what we have
        return ret;
    }

    HfcRest.detect_tls_or_not=function(peer_array){
        var tls = false;
        if(peer_array[0] && peer_array[0].api_port_tls){
            if(!isNaN(peer_array[0].api_port_tls)) tls = true;
        }
        return tls;
    }

    //loop here, check if chaincode is up and running or not
     HfcRest.check_if_deployed=function(e, attempt){
        if(e){
            this.cb_deployed(e);																		//looks like an error pass it along
        }
        else if(attempt >= 15){																	//tried many times, lets give up and pass an err msg
            console.log('[preflight check]', attempt, ': failed too many times, giving up');
            var msg = 'chaincode is taking an unusually long time to start. this sounds like a network error, check peer logs';
            if(!process.error) process.error = {type: 'deploy', msg: msg};
            HfcRest.cb_deployed(msg);
        }
        else{
            console.log('[preflight check]', attempt, ': testing if chaincode is ready');
            chaincode.query.read(['abc'], function(err, resp){
            //chaincode.query.read(['_opentrades'], function(err, resp){
                var cc_deployed = false;
                try{
                    if(err == null){															//no errors is good, but can't trust that alone
                        if(resp != 'null') cc_deployed = true;									//looks alright, brand new, no marbles yet
                        else{
                            var json = JSON.parse(resp);
                            if(json.constructor === Array) cc_deployed = true;					//looks alright, we have marbles
                        }
                    }
                }
                catch(e){}																		//anything nasty goes here

                // ---- Are We Ready? ---- //
                if(!cc_deployed){
                    console.log('[preflight check]', attempt, ': failed, trying again');
                    setTimeout(function(){
                        HfcRest.check_if_deployed(null, ++attempt);										//no, try again later
                    }, 10000);
                }
                else{
                    console.log('[preflight check]', attempt, ': success');
                    HfcRest.cb_deployed(null);															//yes, lets go!
                }
            });
        }
    }

 HfcRest.cb_deployed=function(e){
        if(e != null){
            console.log('! looks like a deploy error, holding off on the starting the socket\n', e);
        }
        else{
            console.log('------------------------------------------ Websocket Up ------------------------------------------');
            /*setInterval(function(){
                console.log("get blocks start .......");
                var mybs = wsRest.getBlocks();
                //console.log(bs);
                let i = 0;
                for(i = 0; i < mybs.length-1; i++){
                    let tmpblock = mybs[i];
                    console.log(tmpblock);
                    let h = tmpblock.blockheight;
                    let qstr = {"blockheight":h};
                    let tmprs = null;
                    try{
                        let all = mycbops.find().fetch();
                        if(all.length >  0){
                            tmprs = mycbops.find(qstr).fetch();
                        }
                    }catch(e){
                        tmprs = null;
                    }
                    //console.log("rs cccccccccccccc="+JSON.stringify(tmprs));
                    if(tmprs == null || tmprs.length == 0){
                        mycbops.insert(tmpblock);
                        console.log("insert blocks "+tmpblock);
                    }
                    };
                console.log("get blocks end .......");

                }, 10000);*/


            //var ruser = ws_hfc.registerUser("xian","111111111111");
            //console.log("register"+ruser);

            //["tradecustomid", "fromuser", "touser", "projectid", "tradecontent"] 
       /* var ds = {
                type:"open_trade",
                tradecustomid:"t3",
                fromuser:"bob",
                touser:"alice",
                projectid:"fp-2",
                tradecontent:"申请 100万"
            }
            var omsf = ws_hfc.open_trade_invoke(ds);
            console.log(omsf);*/

           // var optrades = ws_hfc.getAllTrades("_opentrades");
           // console.log(optrades);

           /* var ds = {
                type:"perform_trade",
                tradecustomid:"t3",
                flag:"审批通过 1，转100万"
            }
            var pmsf = ws_hfc.perform_trade_invoke(ds);
            console.log(pmsf);*/

          

            //var bobq = ws_hfc.getQuery('abc');
            //console.log(bobq);
            //var aliceq = ws_hfc.getQuery('alice');
            //console.log(aliceq);

            /*var bss = wsRest.getBlocks();
            if(bss != null){
                console.log(bss);
            }*/
            
        }
    }

HfcRest.startup_fabric=function(){

   // try{
        var manual = JSON.parse(fs.readFileSync('/Users/jiangbuyun/go/src/github.com/fp/fp/server/hfc/mycreds_docker_compose.json', 'utf8'));
        var peers = manual.credentials.peers;
        console.log('loading hardcoded peers');
        var myusers = null;																			//users are only found if security is on
        if(manual.credentials.users) myusers = manual.credentials.users;
        console.log('loading hardcoded users');
    //}
   // catch(e){
   //     console.log(e);
   //     console.log('Error - could not find hardcoded peers/users, this is okay if running in bluemix');
   // }

    var options = 	{
                        network:{
                            peers: [peers[0]],																	//lets only use the first peer! since we really don't need any more than 1
                            users: this.prefer_type1_users(myusers,myusers),													//dump the whole thing, sdk will parse for a good one
                            options: {
                                        quiet: true, 															//detailed debug messages on/off true/false
                                        tls: this.detect_tls_or_not(peers), 											//should app to peer communication use tls?
                                        maxRetry: 1																//how many times should we retry register before giving up
                                    }
                        },
                        chaincode:{
                            zip_url: 'https://github.com/ibm-blockchain/marbles/archive/v2.0.zip',		
                            unzip_dir: '/Users/jiangbuyun/go/src/github.com/fp/fp/chaincode',													//subdirectroy name of chaincode after unzipped
                            git_url: 'github.com/fp/fp/chaincode',						//GO get http url
                        
                            //hashed cc name from prev deployment, comment me out to always deploy, uncomment me when its already deployed to skip deploying again
                            //deployed_name: '16e655c0fce6a9882896d3d6d11f7dcd4f45027fd4764004440ff1e61340910a9d67685c4bb723272a497f3cf428e6cf6b009618612220e1471e03b6c0aa76cb'
                            deployed_name: '283830b457c5c9371e261500b309bf77efc632e537f4150e91d8c17ebe878e46056b39ef3e0cd41992d050b30ca726c4656e1eca017b91c62d2800947fb6336e'
                            
                        }
                    };


    																		//sdk will populate this var in time, lets give it high scope by creating it here
    ibc.load(options, function (err, cc){														//parse/load chaincode, response has chaincode functions!
        if(err != null){
            console.log('! looks like an error loading the chaincode or network, app will fail\n', err);
            //if(!process.error) process.error = {type: 'load', msg: err.details};				//if it already exist, keep the last error
        }
        else{
            chaincode = cc;
            wsRest.setup(ibc, cc);																
            
            // ---- To Deploy or Not to Deploy ---- //
            if(!cc.details.deployed_name || cc.details.deployed_name === ''){					//yes, go deploy
                cc.deploy('init', ['99'], {delay_ms: 30000}, function(e){ 						//delay_ms is milliseconds to wait after deploy for conatiner to start, 50sec recommended
                    HfcRest.check_if_deployed(e, 1);
                });
            }
            else{																				//no, already deployed
                console.log('chaincode summary file indicates chaincode has been previously deployed');
                HfcRest.check_if_deployed(null, 1);
            }
        }
    });
};


